package com.gohome.gohomechat.model;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.util.Log;

import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.exceptions.EaseMobException;
import com.gohome.gohomechat.GoHomeModel;
import com.gohome.gohomechat.R;
import com.gohome.gohomechat.application.BaseApplication;
import com.gohome.gohomechat.model.entify.Friend;
import com.gohome.gohomechat.model.modellistener.SelectorContantModelListener;
import com.gohome.gohomechat.presenter.callback.SelectorContantCallBack;
import com.gohome.gohomechat.utils.ImageUtil;
import com.gohome.gohomechat.utils.ToastUtil;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.SaveCallback;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by dllo on 16/3/11.
 */
public class SelectorContantModel implements SelectorContantModelListener {
    private Handler handler = new Handler();
    private List<Friend> datas = new ArrayList<>();

    @Override
    public void createGroup(final String groupName, final String dec, final boolean isPublic, final boolean isInvitation, final String[] members, final SelectorContantCallBack callBack) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (isPublic) {

                    try {
                        EMGroupManager.getInstance().createPublicGroup(groupName, dec, members, !isInvitation);//需异步处理

                   //     savePraseGroup(groupName, callBack);
                          callBack.success();
                    } catch (EaseMobException e) {
                        callBack.failed();
                    }
                } else {
                    try {
                        EMGroupManager.getInstance().createPrivateGroup(groupName, dec, members, true);//需异步处理
                  //      savePraseGroup(groupName, callBack);
                        callBack.success();
                    } catch (EaseMobException e) {
                        callBack.failed();
                    }
                }
            }
        }).start();

    }

    @Override
    public void requestData(final SelectorContantCallBack callBack) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                List<String> usernames = null;//需异步执行
                try {
                    usernames = EMContactManager.getInstance().getContactUserNames();

                    ParseQuery<ParseObject> parseQuery = new ParseQuery("AllUserGoHome");
                    parseQuery.whereContainedIn("username", usernames);
                    final List<String> finalUsernames = usernames;
                    parseQuery.findInBackground(new FindCallback<ParseObject>() {
                        @Override
                        public void done(List<ParseObject> objects, ParseException e) {
                            if (e == null) {
                                for (int i = 0; i < objects.size(); i++) {
                                    ParseFile parseFile = objects.get(i).getParseFile("head_img");
                                    datas.add(new Friend(finalUsernames.get(i), parseFile.getUrl()));
                                    Log.i("wcl", parseFile.getUrl());
                                }
                                Collections.sort(datas); // 升序排列
                                GoHomeModel.getInstance().setIsLoginFirst(false);
                                callBack.requestData(datas);
                            } else {
                                Log.i("wcl", e.getMessage() + "  lll");
                            }
                        }
                    });

                    ToastUtil.showToast(datas.size() + " ///");
                } catch (EaseMobException e) {
                    Log.i("uiui", e.getMessage() + "失败");
                    callBack.failed();
                }

            }
        });
    }

//    public void savePraseGroup(final String name, final SelectorContantCallBack callBack) {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    List<EMGroup> grouplist = EMGroupManager.getInstance().getGroupsFromServer();//需异步处理
//                    Log.i("wcll", grouplist.size() + "aaa" + name);
//                    for (EMGroup emGroup : grouplist) {
//                        Log.i("wcll", "进入循环" + emGroup.getGroupName());
//                        if (emGroup.getGroupName().equals(name)) {
//                            Log.i("wcll", "有相等的名字");
//                            // 保存数据
//                            final ParseObject parseObject1 = new ParseObject("AllGroupGoHome");
//                            parseObject1.put("groupname", name);
//                            parseObject1.put("groupid", emGroup.getGroupId());
//                            Bitmap bitmap = BitmapFactory.decodeResource(BaseApplication.getContext().getResources(), R.mipmap.header);
//                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
//                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//                            byte[] byteArray = baos.toByteArray();
//                            //  ImageUtil.compressImageByPixel(bitmap,"headergroup+xx");
//                            final ParseFile parseFile = new ParseFile(emGroup.getGroupId() + "head.png", byteArray);
//                            parseFile.saveInBackground(new SaveCallback() {
//                                @Override
//                                public void done(ParseException e) {
//                                    if (e == null) {
//                                        Log.i("wcll", "群组上传tupian成功");
//
//                                        parseObject1.put("grouphead_img", parseFile);
//                                        parseObject1.saveInBackground(new SaveCallback() {
//                                            @Override
//                                            public void done(ParseException e) {
//                                                if (e == null)
//                                                    callBack.success();
//                                                    //   Log.i("wcll", "群组上传Parse成功");
//                                                else {
//                                                    callBack.failed();
//                                                    Log.i("wcll", "群组上传Parse失败"+e.getMessage());
//                                                }
//                                            }
//                                        });
//                                    } else {
//                                        callBack.failed();
//                                        Log.i("wcl", "群组上传tupian失败"+e.getMessage());
//                                    }
//                                }
//                            });
//                        }
//                    }
//                } catch (EaseMobException e) {
//                    callBack.failed();
//                    Log.i("wcl", e.getMessage() + " asdfsdaf");
//                }
//            }
//        }).start();
//    }
}
